<template>
  <nut-popup
    v-model:visible="healthStore.showAdd"
    position="bottom"
    :style="{ height: '80%' }"
    closeable
    close-icon-position="top-right"
    round
    safe-area-inset-bottom
  >
    <view class="popup-container">
      <!-- 标题栏 -->
      <view class="popup-header">
        <text class="popup-title">手动记录数据</text>
      </view>

      <view class="popup-content">
        <!-- 左侧导航栏 -->
        <view class="sidebar">
          <view
            v-for="(item, index) in navList"
            :key="index"
            class="nav-item"
            :class="{ active: currentNav === item.value }"
            @tap="handleNavClick(item.value)"
          >
            <text>{{ item.label }}</text>
          </view>
        </view>

        <!-- 右侧内容区 -->
        <view class="content">
          <!-- 表单区域 -->
          <view class="form-container">
            <!-- 动态渲染表单项 -->
            <view
              v-for="(field, index) in currentFormFields"
              :key="index"
              class="form-item"
            >
              <text class="label">{{ field.label }}</text>
              <input
                v-model="formData[field.key]"
                :type="field.type || 'digit'"
                class="input-field"
                :placeholder="field.placeholder"
                :maxlength="field.maxlength"
              />
              <view class="unit-row">
                <text class="unit">{{ field.unit }}</text>
                <text class="range">{{ field.range }}</text>
              </view>
            </view>
          </view>

          <!-- 提交按钮 -->
          <view class="button-container">
            <nut-button
              type="success"
              size="large"
              class="submit-btn"
              @click="submitForm"
            >
              提交数据
            </nut-button>
          </view>
        </view>
      </view>
    </view>
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useHealthStore } from '@/store'
import { request } from '@/service/request'
import Taro from '@tarojs/taro'
import { useEmitter } from '@/hooks/common'
// import { ref, onMounted } from 'vue'
// import { useHealthStore } from '@/store/modules/health'

// 使用 health store
const healthStore = useHealthStore()
const emitter = useEmitter()

// 导航列表
const navList = [
  { label: '血压心率', value: 'bloodPressure' },
  { label: '血氧', value: 'oxygen' },
  { label: '血糖', value: 'bloodSugar' },
  { label: '体温', value: 'bodyTemp' },
  { label: '血脂', value: 'bloodLipid' },
  { label: '尿酸', value: 'uricAcid' },
  { label: '睡眠评分', value: 'sleepScore' },
  { label: 'BMI', value: 'bmi' },
  { label: '体重', value: 'weight' },
  { label: '运动其他', value: 'exercise' },
]

// 表单字段配置
const formFieldsConfig: Record<string, Array<{
  key: string
  label: string
  type: string
  placeholder: string
  maxlength: number
  unit: string
  range: string
}>> = {
  bloodPressure: [
    {
      key: 'systolic',
      label: '收缩压',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 5,
      unit: '单位:mmHg',
      range: '正常范围值:90 -- 140',
    },
    {
      key: 'diastolic',
      label: '舒张压',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 5,
      unit: '单位:mmHg',
      range: '正常范围值:60 -- 90',
    },
    {
      key: 'heartRate',
      label: '心率',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 3,
      unit: '单位:bpm',
      range: '正常范围值:60 -- 90',
    },
  ],
  oxygen: [
    {
      key: 'oxygenSaturation',
      label: '血氧饱和度',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 3,
      unit: '单位:%',
      range: '正常范围值:95 -- 100',
    },
  ],
  bloodSugar: [
    {
      key: 'bloodGlucose',
      label: '血糖值',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 5,
      unit: '单位:mmol/L',
      range: '正常范围值:3.9 -- 6.1',
    },
  ],
  bodyTemp: [
    {
      key: 'temperature',
      label: '体温',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 4,
      unit: '单位:℃',
      range: '正常范围值:36.0 -- 37.2',
    },
  ],
  bloodLipid: [
    {
      key: 'cholesterol',
      label: '总胆固醇',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 5,
      unit: '单位:mmol/L',
      range: '正常范围值:<5.2',
    },
    {
      key: 'triglycerides',
      label: '甘油三酯',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 5,
      unit: '单位:mmol/L',
      range: '正常范围值:<1.7',
    },
  ],
  uricAcid: [
    {
      key: 'uricAcid',
      label: '尿酸',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 5,
      unit: '单位:μmol/L',
      range: '正常范围值:男性208-428，女性155-357',
    },
  ],
  sleepScore: [
    {
      key: 'sleepScore',
      label: '睡眠质量评分',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 3,
      unit: '单位:分',
      range: '正常范围值:70 -- 100',
    },
  ],
  bmi: [
    {
      key: 'bmi',
      label: 'BMI指数',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 4,
      unit: '单位:kg/m²',
      range: '正常范围值:18.5 -- 23.9',
    },
  ],
  weight: [
    {
      key: 'weight',
      label: '体重',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 5,
      unit: '单位:kg',
      range: '正常范围值:因人而异',
    },
  ],
  exercise: [
    {
      key: 'exerciseTime',
      label: '运动时长',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 4,
      unit: '单位:分钟',
      range: '建议:每天30分钟以上',
    },
    {
      key: 'calories',
      label: '消耗卡路里',
      type: 'digit',
      placeholder: '请输入测量数据',
      maxlength: 5,
      unit: '单位:千卡',
      range: '因运动强度而异',
    },
  ],
}

// 表单数据
const formData = ref<Record<string, string>>({
  // 血压心率
  systolic: '',
  diastolic: '',
  heartRate: '',
  // 血氧
  oxygenSaturation: '',
  // 血糖
  bloodGlucose: '',
  // 体温
  temperature: '',
  // 血脂
  cholesterol: '',
  triglycerides: '',
  // 尿酸
  uricAcid: '',
  // 睡眠评分
  sleepScore: '',
  // BMI
  bmi: '',
  // 体重
  weight: '',
  // 运动
  exerciseTime: '',
  calories: '',
})

// 当前选中导航
const currentNav = ref('bloodPressure')

// 当前表单字段
const currentFormFields = computed(() => {
  return formFieldsConfig[currentNav.value] || []
})

// 导航点击处理
const handleNavClick = (value: string) => {
  currentNav.value = value
}

// 重置表单数据
const resetFormData = () => {
  Object.keys(formData.value).forEach(key => {
    formData.value[key] = ''
  })
}

// 表单提交
const submitForm = async () => {
  // 获取当前页面的表单数据
  const currentData: Record<string, string> = {}
  currentFormFields.value.forEach((field: any) => {
    if (formData.value[field.key]) {
      currentData[field.key] = formData.value[field.key]
    }
  })

  // 提交数据

  // 检查是否有数据
  if (Object.keys(currentData).length === 0) {
    Taro.showToast({
      title: '请填写数据',
      icon: 'none'
    })
    return
  }

  try {
    // 构建提交数据
    const submitData = {
      proName: '常规项目', // 项目大类名称
      subName: getSubNameByNav(currentNav.value), // 项目子类名称
      subValue: 10, // 项目子类码值，固定为10
      subRes: Object.values(currentData).join('/'), // 项目检查结果值，多个值用/分隔
      updateTime: new Date().toISOString().split('T')[0]
    }

    // 提交到接口的数据

    // 调用接口
    const { error, success } = await request.post('/health_records/health_basepro/healthBaseProjectInfo/add', submitData, {
      useErrMsg: true
    })

    if (!error && success) {
      Taro.showToast({
        title: '提交成功',
        icon: 'success'
      })
      
      // 发送事件通知刷新健康数据列表
      emitter.$emit('refreshHealthData')
      
      // 提交成功后关闭弹出框
      healthStore.showAdd = false
      
      // 重置表单
      resetFormData()
    } else {
      Taro.showToast({
        title: '提交失败',
        icon: 'none'
      })
    }
  } catch (error) {
    Taro.showToast({
      title: '提交失败',
      icon: 'none'
    })
  }
}

// 根据导航获取子类名称
const getSubNameByNav = (navValue: string): string => {
  const navMap: Record<string, string> = {
    'bloodPressure': '血压·心率',
    'oxygen': '血氧',
    'bloodSugar': '血糖',
    'bodyTemp': '体温',
    'bloodLipid': '血脂',
    'uricAcid': '尿酸',
    'sleepScore': '睡眠评分',
    'bmi': 'BMI',
    'weight': '体重',
    'exercise': '运动'
  }
  return navMap[navValue] || navValue
}
</script>

<style lang="scss">
/* 弹出框容器 */
.popup-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

/* 标题栏 */
.popup-header {
  background-color: #fff;
  padding: 32rpx 0;
  text-align: center;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

/* 内容区域 */
.popup-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 侧边导航 */
.sidebar {
  width: 180rpx;
  background-color: #fff;
  border-right: 1rpx solid #eee;
  overflow-y: auto;
}

.nav-item {
  padding: 30rpx 20rpx;
  font-size: 28rpx;
  color: #333;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-item.active {
  background-color: #f0f9eb;
  color: #4caf50;
  position: relative;
}

.nav-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 50%;
  background-color: #4caf50;
}

/* 内容区域 */
.content {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

/* 表单容器 */
.form-container {
  flex: 1;
  padding: 30rpx;
  background-color: #fff;
}

/* 表单项 */
.form-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
  color: #333;
}

.input-field {
  width: 100%;
  height: 80rpx;
  background-color: #f7f7f7;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 30rpx;
  margin-bottom: 20rpx;
  border: 1rpx solid #e5e5e5;
}

.unit-row {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  color: #999;
}

.unit {
  color: #666;
}

.range {
  color: #999;
}

/* 按钮容器 */
.button-container {
  padding: 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 88rpx;
}

</style>
